/*
 * Copyright (C) 2011, 2012 Moravská zemská knihovna v Brně / Moravian Library in Brno
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cz.mzk.oai.provider.response.listRequests;

import java.io.IOException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class ResumptionTokenManager {

    private static final Logger logger = Logger.getLogger(ResumptionTokenManager.class.getName());
    private static ResumptionTokenManager listIdentifiersInst;
    private static ResumptionTokenManager listRecordsInst;
    //instance data
    private ResumptionTokens tokens = new ResumptionTokens();
    private int returnRecords = 5;

    public static ResumptionTokenManager instanceOf(ListRequestType type, int returnRecords) {
        if (type == ListRequestType.LIST_IDENTIFIERS) {
            if (listIdentifiersInst == null) {
                listIdentifiersInst = new ResumptionTokenManager(returnRecords);
            }
            return listIdentifiersInst;
        } else if (type == ListRequestType.LIST_RECORDS) {
            if (listRecordsInst == null) {
                listRecordsInst = new ResumptionTokenManager(returnRecords);
            }
            return listRecordsInst;
        } else {
            return null;
        }
    }

    private ResumptionTokenManager(int returnRecords) {
        this.returnRecords = returnRecords;
    }

    public synchronized static void clearOldResumptionTokens() {
        if (listIdentifiersInst != null) {
            listIdentifiersInst.clearElderlyResumptionTokens();
        }
        if (listRecordsInst != null) {
            listRecordsInst.clearElderlyResumptionTokens();
        }
    }

    private void clearElderlyResumptionTokens() {
        for (RequestSequence resumption : tokens.values()) {
            if (timeToDie(resumption)) {
                String uuid = uuidFromResultPart(resumption);
                logger.log(Level.INFO, "Removing resumption token {0} which was valid until {1}", new Object[]{uuid, resumption.getValidUntil().toString()});
                boolean removed = tokens.values().remove(resumption);
            }
        }
    }

    private boolean timeToDie(RequestSequence resumption) {
        return resumption.getValidUntil().isBeforeNow();
    }

    private String uuidFromResultPart(RequestSequence resumption) {
        for (String uuid : tokens.keySet()) {
            if (resumption.equals(tokens.get(uuid))) {
                return uuid;
            }
        }
        return null;
    }

    public synchronized String registerNextResultPart(RequestSequence part) throws IOException {
        RequestSequence nextPart = part.nextPart();
        if (nextPart != null) {
            String resumptionToken = generateNotColidingUuid();
            logger.log(Level.INFO, "registering new resumption token {0}", resumptionToken);
            tokens.put(resumptionToken, nextPart);
            return resumptionToken;
        } else {
            return null;
        }
    }

    public RequestSequence requestSeqFromResToken(String resumptionToken) {
        RequestSequence resumption = tokens.get(resumptionToken);
        return resumption;
    }

    public int returnedRecords() {
        return returnRecords;
    }

    private static String generateNotColidingUuid() {
        UUID uuid;
        do {
            uuid = UUID.randomUUID();
        } while (resumptionTokenUsed(uuid.toString()));
        return uuid.toString();
    }

    private static boolean resumptionTokenUsed(String resumptionToken) {
        return (listIdentifiersInst != null && listIdentifiersInst.containsResumptionToken(resumptionToken))
                || (listRecordsInst != null && listRecordsInst.containsResumptionToken(resumptionToken));
    }

    private boolean containsResumptionToken(String resumptionToken) {
        return tokens.keySet().contains(resumptionToken);
    }
}
